<template>
  <div class="UserLayout cacp" >
    <a-layout class="content-layout">
      <a-layout>
        <a-layout-header class="header" style="position: relative" v-if="loaded">
          <h3 title="返回首页" @click="$router.push('/')">“甬网智享”网络空间综合治理智控平台</h3>
          <!-- <a-icon type="left"></a-icon> -->
          <div class="header-action" v-if="loadeds">
            <div class="header-tab" v-if="meta.type === 'home'">
              <a-radio-group v-model="homeType" @change="changeTab" class="header-tab-radio" size="large" button-style="solid">
                <a-radio-button value="/home/normal">日常面板</a-radio-button>
                <a-radio-button class="dangers" value="/home/danger">应急面板</a-radio-button>
              </a-radio-group>
            </div>
            <div class="header-tab" v-else-if="meta.type === 'event'">
              <a-radio-group v-model="eventType" @change="changeTab" class="header-tab-radio" size="large" button-style="solid">
                <a-radio-button value="/handleEvent/index">处置事件</a-radio-button>
                <a-radio-button value="/handleEvent/watch">观察事件</a-radio-button>
              </a-radio-group>
            </div>
            <span v-else>{{ meta.title }}{{titleName}}</span>
          </div>
          <div class="header-right">
            <!-- <div class="flex statistic-countdown">
              自动刷新倒计时：
              <a-statistic-countdown
                :value="deadline"
                style="margin-right: 50px"
                @finish="onFinish"
              />
            </div> -->
            <!-- <div class="back-icon" title="返回上一页" v-if="$route.path != '/home/normal' && $route.path != '/home/danger'" style="margin-right: 20px;" @click="$router.go(-1)">
              <a-icon type="left-circle" />
              <span style="font-size: 14px;">返回上页</span>
            </div> -->
            <div class="refresh-btn" title="返回上一页" v-if="$route.path != '/home/normal' && $route.path != '/home/danger'" style="margin-right: 20px;" @click="$router.go(-1)">
              <a-icon type="left-circle" />
              返回上页
              <!-- <a-statistic-countdown
                v-if="eventType == '/home/normal'"
                :value="deadline"
                @finish="onFinish"
              /> -->
            </div>
            <div class="refresh-btn" @click="refresh">
              <a-icon type="redo" />
              刷新
              <!-- <a-statistic-countdown
                v-if="eventType == '/home/normal'"
                :value="deadline"
                @finish="onFinish"
              /> -->
            </div>
            <div class="tip-type"> {{ plantType == 2 ? '专网版' : '互联网版' }} </div>

            <a-popover placement="bottomRight" v-if="!isShare">
              <template slot="content">
                <div class="notice-header-card scroll">
                  <div class="notice-history" @click="showModal=true">历史记录</div>
                  <template v-if="notice.length">
                    <div class="notice-header-cnt" @click="showDetail(item)" v-for="item in notice" :key="item.id">
                      <h1>通知人：{{ item.createBy }}</h1>
                      <div v-if="item.isWatch == 1" :class="['notice-header-status', 'readed']">已读</div>
                      <div v-else :class="['notice-header-status']">未读</div>
                      <p class="ellipsis-2">{{ item.content }}</p>
                      <p style="text-align: right;font-size: 12px">{{ item.createTime }}</p>
                    </div>
                  </template>
                  <a-empty style="margin-top: 80px" v-else description="暂无通知" />
                </div>
              </template>
              <a-badge :count="notice && notice[0] ? notice[0].num : ''">
                <a-icon type="bell" class="bell-icon" theme="filled" />
              </a-badge>
            </a-popover>

            <a-dropdown placement="bottomCenter" v-if="!isShare">
              <a class="ant-dropdown-link" @click="e => e.preventDefault()" style="margin-left: 30px">
                <a-avatar class="avatar-icon" :size="40" icon="user" />
                <span class="userName">{{ userInfo.realName }}</span>
                <a-icon type="caret-down" class="caret-down" theme="filled" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a href="javascript:;" @click="editPwd">修改密码</a>
                </a-menu-item>
                <a-menu-item>
                  <a href="javascript:;" @click="loginOut">退出登录</a>
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </div>
        </a-layout-header>
        <a-layout>
          <!-- <a-layout-sider v-model="collapsed" :trigger="null" collapsible>
            <Menu />
          </a-layout-sider> -->
          <a-layout-content id="visibleOperPanel">

            <div class="content" :style="{background: contentBg}">
              <router-view v-if="loaded"></router-view>
            </div>
          </a-layout-content>
        </a-layout>
      </a-layout>
    </a-layout>

    <!-- <UpdatesPwd ref="UpdatesPwd" @submit="submitPwd" /> -->
    <NoticeDetail v-model="show" :id="id" @cancel="cancel" />

    <NoticeHistory v-model="showModal" />

    <a-modal
      :visible="showPwd"
      :width="880"
      title="修改密码"
      @cancel="showPwd = false"
      @ok="handleConfirm"
    >
      <a-form-model
        ref="ruleForm1"
        :model="pwdForm"
        :rules="pwdRule"
        style="margin-bottom:20px"
        v-bind="formItemLayout">
        <a-form-model-item label="原密码" prop="oldpassword">
          <a-input
            v-model="pwdForm.oldpassword"></a-input>
        </a-form-model-item>
        <a-form-model-item label="新密码" prop="password">
          <a-input v-model="pwdForm.password"></a-input>
        </a-form-model-item>
        <a-form-model-item label="确认新密码" prop="confirmpassword">
          <a-input
            v-model="pwdForm.confirmpassword"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { PageHeader } from '@/layouts';
import Menu from '@/components/Menu';
import { queryIssueUser } from '@/api/notice';
import { queryWebTimeDetail } from '@/api/serve';
import NoticeDetail from './NoticeDetail';
import NoticeHistory from './NoticeHistory';
import { updateUserPassword, logout } from '@/api/user';

// import moment from 'moment';
// import UpdatesPwd from '@/views/system/components/UpdatesPwd';
const reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$/;

let noticeINT = '';
export default {
  name: 'UserLayout',
  provide() {
    return {
      refresh: this.refresh,
      setTitle: this.setTitle,
      toURL: this.toURL,
      toLink: this.toLink,
      toDetail: this.toDetail
    };
  },

  data() {
    const that = this;
    function validator(rule, value, callback) {
        if (!value) {
            callback(new Error('新密码不能为空！'));
        } else if (!reg.test(value)) {
            callback(new Error('密码必须8-16位且包含数字，大写字母，小写字母，特殊字符中的任意三种！'));
        } else {
            callback();
        }
    }
    function validatorConfirm(rule, value, callback) {
        if (!value) {
            callback(new Error('密码不能为空！'));
        } else if (that.pwdForm.password != value) {
            callback(new Error('密码不一致！！'));
        } else {
            callback();
        }
    }
    return {
      showModal: false,
      showPwd: false,
      id: '',
      title: '',
      homeType: '/home/normal',
      eventType: '/handleEvent/index',
      // showSmall: false,
      pwdForm: {

      },
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 14 }
        }
      },
      pwdRule: {
        oldpassword: [{ required: true, message: '旧密码不能为空' }],
        password: [{ required: true, validator }],
        confirmpassword: [{ required: true, validator: validatorConfirm }]
      },
      tree: [],
      collapsed: false,
      showRight: true,
      areaName: '',
      show: false,
      loaded: true,
      reload: true,
      menus: [],
      area: [
      ],
      loadeds: true,
      notice: [],
      contentBg: '',
      deadline: Date.now() + 10 * 1000,
      plantType: process.env.VUE_APP_TYPE
    };
  },
  filters: {
  },
  components: {
    PageHeader,
    Menu,
    NoticeDetail,
    NoticeHistory
    // UpdatesPwd
  },

  computed: {

    titleName() {
      let key = this.$route.query.key
      if (key === 'cz') {
        return '-处置事件'
      } else if (key === 'gc') {
        return  '-观察事件'
      }
      return  ''
    },
    ...mapState({
      userInfo: (state) => state.user.userInfo
    }),
    meta() {
      const { meta } = this.$route;
      return meta || {};
    },
    isShare() {
      return this.$route.path == '/detail/index' && this.$route.query.type == 5;
    }
    // ...mapGetters(['userInfo'])
  },
  watch: {
    '$route.path'(e) {
      console.log('wat $route.path');
      this.homeType = this.$route.path;
      this.eventType = this.$route.path;
      if (e == '/home/danger') {
        this.contentBg = 'rgb(255,245,238)';
      } else if (e == '/home/normal') {
        this.queryTime();
        this.contentBg = 'none';
      } else {
        this.contentBg = 'none';
      }
      // this.queryIssueUser();
    }
  },
  updated() {

  },
  created() {
    this.homeType = this.$route.path;
    this.eventType = this.$route.path;
    this.queryTime();
  },
  mounted() {
    if (!this.isShare) {
      this.queryIssueUser();
      noticeINT = setInterval(() => {
        this.queryIssueUser();
      }, 5000);
    }
  },
  beforeDestroy() {
    noticeINT && clearInterval(noticeINT);
  },
  methods: {
    editPwd() {
      this.showPwd = true;
    },
    queryTime() {
      queryWebTimeDetail().then(res => {
        this.deadline = Date.now() + (res.data.refreshCycle || 90) * 1000;
      });
    },
    cancel() {
      this.queryIssueUser();
    },
    queryIssueUser() {
      queryIssueUser({
        id: this.userInfo.uid
      }).then(res => {
        // console.log(res);
        this.notice = res.data.records;
      });
    },
    updateTitle() {

    },
    refresh() {
      this.loaded = false;

      this.$nextTick(() => {
        this.loaded = true;
      });
    },
    showDetail({ id }) {
      this.id = id;
      this.show = true;
    },

    reset(m) {
      this.reload = false;

      this.$nextTick(() => {
        this.reload = true;
      });

      console.log('reset', this.menus);
    },

    loginOut() {
      logout().then(() => {
        this.$ls.clear();
        this.$ss.clear();
        this.$router.push({ path: '/user/login' });
      });
    },
    setTitle(title) {
      console.log('title');
      this.title = title;
      this.loadeds = false;
      this.$nextTick(() => {
        this.loadeds = true;
      });
    },

    changeTab(e) {
      this.$router.push({ path: e.target.value });
      console.log(e.target.value);
    },

    toURL(path) {
      if (path) this.$router.push({ path });
    },
    toLink({ link }) {
      if (link) window.open(link);
    },

    toDetail(item, key, type) {
      console.log(item, key, type);
      this.$router.push({ path: '/detail', query: { id: item.id, typeId: item.typeId, key, type } });
    },
    onFinish() {
      this.queryTime();
      // this.$bus.$emit('refresh');
    },
    handleConfirm() {
      this.$refs.ruleForm1.validate((valid) => {
        if (valid) {
          if (this.pwdForm.password !== this.pwdForm.confirmpassword) {
              this.$message.error('两次密码输入不一致');
          } else {
            console.log(this.userInfo);
            updateUserPassword({
                username: this.userInfo.username,
                password: this.pwdForm.password,
                oldPassword: this.pwdForm.oldpassword,
                id: this.userInfo.uid
            }).then(res => {
                this.$message.success(res.msg);
                this.pwdForm.password = '';
                this.pwdForm.confirmpassword = '';
                this.pwdForm.oldpassword = '';
                this.$nextTick(() => {
                    this.$refs['ruleForm1'].clearValidate();
                });
                this.modalShow.show1 = false;
            });
          }
        }
      });
    }
  }

};

</script>
<style lang="less">
  .notice-header-card {
    width: 320px;
    height: 380px;
    overflow-y: auto;
    padding-right: 10px;
    .notice-history {
      position: absolute;
      right: 20px;
      cursor: pointer;
    }
    .notice-header-cnt {
      position: relative;
      padding: 12px 0;
      border-bottom: 1px solid #ddd;
      margin-top: 8px;
      h1,p {
        margin: 0;
      }
      h1 {
        font-size: 16px;
        font-weight: 400;
        color: #1F3B8A;
        line-height: 1.4;
        margin-bottom: 12px;
        max-width: 90%;
        cursor: pointer;
      }
      p {
        font-size: 14px;
        font-weight: 400;
        color: #999999;
        line-height: 18px;
        &:last-child {
          line-height: 1;
          margin-top: 4px;
        }
      }
      .notice-header-status {
        position: absolute;
        right: 0;
        top: 12px;
        font-size: 14px;
        color: red;
        &.readed {
           color: rgb(185, 185, 185);
        }

      }
    }
  }
</style>
<style lang="less" scoped>
  .userName {
    font-size: 15px;
    color: #1F3B8A;
    margin-left: 8px;
    font-weight: 500;
  }
  .UserLayout {
    h3 {
      font-size: 22px;
      font-weight: 500;
      color: #012273;
      margin: 0;
      cursor: pointer;
      // line-height: 28px;
    }

    .header {
      position: relative;
    }

    .header-action {
      position: absolute;
      left: 50%;
      transform: translate(-50%, 0);
      .header-tab {
        width: 264px;
        height: 44px;
        background: #E2E8F0;
        border-radius: 10px;
      }
      >span {
        font-size: 22px;
        font-weight: 500;
        color: #1F3B8A;
        // line-height: 120px;
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      .refresh-btn {
        min-width: 78px;
        height: 28px;
        padding: 0 12px;
        background: #1F3B8A;
        border-radius: 14px;
        font-size: 15px;
        font-weight: 500;
        color: #FFFFFF;
        line-height: 28px;
        text-align: center;
        cursor: pointer;
        transition: all .3s;
        &:hover {
          background: #3c569e;
        }
      }
      .tip-type {
        font-size: 18px;
        font-weight: 500;
        color: #012273;
        line-height: 28px;
        margin-left: 23px;
        margin-right: 50px;
      }
      .bell-icon {
        color: #82BAFF;
        font-size: 22px;
        cursor: pointer;
        // margin-right: 30px;
      }
      .avatar-icon {
        background: #006BFC;
      }
      .caret-down {
        font-size: 11px;
        color: #006BFC;
        margin-left: 3px;
      }
    }

    .content {
      padding: 12px 20px;
      box-sizing: border-box;
      min-height: 100vh;
      transition: all 1s;
    }
    .back-icon {
      display: flex;
      align-items: center;
      font-size: 20px;
      cursor: pointer;
      >span {
        margin-left: 8px;
      }
    }
    .header-tab-radio {
      display: block;
      margin: 0 auto;
      // width: 118px;
      height: 30px;
      text-align: center;
      // background: #1F3B8A;
      // border-radius: 10px;
      .ant-radio-button-wrapper-checked {
        background: #1F3B8A !important;
        border-color: #1F3B8A !important;
        border-radius: 10px;
        color: #fff !important;
        &.dangers {
          background: #DD2323 !important;
          border-color: #DD2323 !important;

        }
      }
      .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):focus-within {
        box-shadow: 0 0 0 3px rgba(31, 59, 138, 0.08) !important;
      }
      .ant-radio-button-wrapper {
        border-radius: 10px;
        width: 118px;
        height: 30px;
        line-height: 28px;
        text-align: center;
        margin-top: 7px;
        background: none;
        color: #333;
        border-color: transparent;
        transition: none;
        &:first-child {
          margin-right: 8px;
        }
      }
      .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled)::before {
        background-color: transparent;
      }
      .ant-radio-button-wrapper:not(:first-child)::before {
        background: none;
      }
    }
  }
</style>
<style lang="less">
.refresh-btn {
  .ant-statistic {
    display: inline-block;
    margin-left: 2px;
  }
  .ant-statistic-content {
    font-size: 14px !important;
    color: #fff;
  }
}
</style>
